<script setup lang="ts">

import {onMounted, ref, nextTick } from "vue";
import * as UserApis from "@/api/user"
import * as UserTypes from "@/api/user/types"
import * as SystemApis from "@/api/system"
import * as SystemTypes from "@/api/system/types"
import {ElMessage} from "element-plus";
import {useRoute, useRouter} from "vue-router";
import {isEmptyString} from "@/utils/string";
import {Edit, Message} from "@element-plus/icons-vue";
import {useLoginStore} from "@/store/login";
import UserAvatar from "@/components/common/UserAvatar.vue";
import {formatDate} from "@/utils/time";
import SysMessageDialog from "@/components/feedback/SysMessageDialog.vue";

const menuTabs = {
  BASE_INFO: "base",
  MY_MESSAGE: "message",
  SYSTEM_NOTICE: "notice",
  ACCOUNT_BIND: "bound",
  PWD_UPDATE: "pwd",
  LOGOUT: "logout",
}
const route = useRoute()
const router = useRouter()
const loginStore = useLoginStore();
const userId = ref()
const menuTabSelected = ref('base')
const userInfo = ref<UserTypes.UserDetailResp>()
const sysMessageSessionList = ref<SystemTypes.SysMessageSessionResp[]>()
const showSessionChatDialog = ref(false)
const clickSessionId = ref<number>(null)
const baseInfoForm = ref({nickname:"", signature:""})
const pwdForm = ref({oldPwd:'', newPwd:'', confirmNewPwd:''})

const loadUserInfo = () => {
  UserApis.getDetail(userId.value).then(result => {
    userInfo.value = result
    baseInfoForm.value.nickname = result.nickname
    baseInfoForm.value.signature = result.signature
  })
}

const loadSysMessageSessionList = () => {
  SystemApis.querySysMessageSession(userId.value).then(result => {
    sysMessageSessionList.value = result
  })
}

const loadMessageSessionChat = (sessionId: number, callback:Function) => {
  clickSessionId.value = sessionId
  showSessionChatDialog.value = true
  callback()
}

const onClickMenuTab = (tabName: string) => {
  switch (tabName) {
    case menuTabs.LOGOUT:
      loginStore.logout()
      router.push('/')
      break
    case menuTabs.MY_MESSAGE:
      loadSysMessageSessionList()
  }
  menuTabSelected.value = tabName
}
//修改基本信息
const submitBaseInfo = () => {
  if (isEmptyString(baseInfoForm.value.nickname)) {
    ElMessage.error("昵称不能为空！")
    return
  }
  UserApis.updateUserInfo({userId:userInfo.value.id, ...baseInfoForm.value}).then(()=> {
    userInfo.value.nickname = baseInfoForm.value.nickname
    userInfo.value.signature = baseInfoForm.value.signature
    ElMessage.success("更新成功")
  })
}
//修改密码
const submitPwdUpdate = () => {
  if (pwdForm.value.newPwd != pwdForm.value.confirmNewPwd) {
    ElMessage.error("两次密码输入不一致！")
    return
  }
  UserApis.updatePwd({...pwdForm.value}).then(()=> {
    ElMessage.success("更新成功")
  })
}

onMounted(() => {
  userId.value = Number(route.params.userId)
  if (userId.value == null || isNaN(userId.value)) {
    ElMessage({
      type: 'error',
      message: '缺少必要参数'
    })
    return
  }
  menuTabSelected.value = String(route.query?.m ?? 'base')
  onClickMenuTab(menuTabSelected.value)
  loadUserInfo()
})
</script>

<template>
  <div class="w-full h-full overflow-auto bg-white-soft">
    <div class="mt-6">
      <div class="ui FHContainer">
        <div class="FHMain">
          <div class="FHContent">
            <div class="content flex flex-row justify-center">
              <!--左侧nav-->
              <div class="w-[300px]">
                <!--头像和名称-->
                <div class="py-10 px-8 text-center border rounded-lg bg-white mb-5 min-h-[300px]">
                  <div v-if="userInfo">
                    <UserAvatar :size="80" :file-id="userInfo.avatar" class="mb-5"></UserAvatar>
                    <p class="text-lg mb-5">{{ userInfo.nickname }}</p>
                    <p class="text-sm text-gray-500 mb-5">
                      {{ isEmptyString(userInfo.signature) ? '这个人很懒，什么都没有留下～' : userInfo.signature }}</p>
                    <div>
                      <RouterLink to="/article/publish" v-if="userInfo?.allowBlog"><el-button :icon="Edit" type="primary" size="default" style="width: 200px">投稿</el-button></RouterLink>
                    </div>
                  </div>
                  <el-skeleton v-else></el-skeleton>
                </div>
                <!--menu-->
                <div class="bg-white border rounded-lg overflow-hidden">
                  <ul class="menu-ul">
                    <li class="px-6 py-4 border-b relative" :class="{selected: menuTabSelected == menuTabs.BASE_INFO}"
                        @click="onClickMenuTab(menuTabs.BASE_INFO)">
                      <div class="flex items-center select-none">
                        <el-icon size="20" style="color: var(--color-text-primary)" class="mr-3">
                          <User/>
                        </el-icon>
                        基本信息
                      </div>
                    </li>
                    <li class="px-6 py-4 border-b relative" :class="{selected: menuTabSelected == menuTabs.MY_MESSAGE}"
                        @click="onClickMenuTab(menuTabs.MY_MESSAGE)">
                      <div class="flex items-center select-none">
                        <el-icon size="20" style="color: var(--color-text-primary)" class="mr-3">
                          <Message/>
                        </el-icon>
                        我的私信
                      </div>
                    </li>
                    <li class="px-6 py-4 border-b relative"
                        :class="{selected: menuTabSelected == menuTabs.SYSTEM_NOTICE}"
                        @click="onClickMenuTab(menuTabs.SYSTEM_NOTICE)">
                      <div class="flex items-center select-none">
                        <el-icon size="20" style="color: var(--color-text-primary)" class="mr-3">
                          <Bell/>
                        </el-icon>
                        系统通知
                      </div>
                    </li>
<!--                    <li class="px-6 py-4 border-b relative"-->
<!--                        :class="{selected: menuTabSelected == menuTabs.ACCOUNT_BIND}"-->
<!--                        @click="onClickMenuTab(menuTabs.ACCOUNT_BIND)">-->
<!--                      <div class="flex items-center select-none">-->
<!--                        <el-icon size="20" style="color: var(&#45;&#45;color-text-primary)" class="mr-3">-->
<!--                          <Link/>-->
<!--                        </el-icon>-->
<!--                        账号绑定-->
<!--                      </div>-->
<!--                    </li>-->
                    <li class="px-6 py-4 border-b relative" :class="{selected: menuTabSelected == menuTabs.PWD_UPDATE}"
                        @click="onClickMenuTab(menuTabs.PWD_UPDATE)">
                      <div class="flex items-center select-none">
                        <el-icon size="20" style="color: var(--color-text-primary)" class="mr-3">
                          <Lock/>
                        </el-icon>
                        修改密码
                      </div>
                    </li>
                    <li class="px-6 py-4 relative" :class="{selected: menuTabSelected == menuTabs.LOGOUT}"
                        @click="onClickMenuTab(menuTabs.LOGOUT)">
                      <div class="flex items-center select-none">
                        <el-icon size="20" style="color: var(--color-text-primary)" class="mr-3">
                          <House/>
                        </el-icon>
                        退出登录
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
              <!--右侧content-->
              <div class="flex-1 max-w-[1176px] h-[608px]">
                <div class="ml-5 border h-full rounded-lg bg-white">
                  <div v-if="menuTabSelected == menuTabs.BASE_INFO">
                    <div class="px-10 py-5 border-b">
                      <p class="font-bold text-xl">基本资料</p>
                    </div>
                    <div class="mx-10 my-8">
                      <div class="flex flex-row mb-8">
                        <label class="w-[120px] text-gray-500">昵称</label>
                        <div class="flex-1">
                          <el-input size="large" v-model="baseInfoForm.nickname"></el-input>
                        </div>
                      </div>
                      <div class="flex flex-row mb-8">
                        <label class="w-[120px] text-gray-500">个人说明</label>
                        <div class="flex-1">
                          <el-input
                              size="large"
                              v-model="baseInfoForm.signature"
                              maxlength="200"
                              style="width: 100%;"
                              placeholder="写下个人说明，让别人更好了解您（可选）"
                              show-word-limit
                              type="textarea"
                              :autosize="{minRows:4, maxRows:4}"
                              class="mb-3"
                          />
                        </div>
                      </div>
                      <div class="pl-[120px]">
                        <el-button type="primary" @click="submitBaseInfo">保存设置</el-button>
                      </div>
                    </div>
                  </div>
                  <div v-if="menuTabSelected == menuTabs.MY_MESSAGE">
                    <div class="px-10 py-5 border-b">
                      <p class="font-bold text-xl">我的私信</p>
                    </div>
                    <div class="mx-10 my-8">
                      <ul v-if="sysMessageSessionList?.length > 0">
                        <li v-for="session in sysMessageSessionList" class="session-item"
                            @click="loadMessageSessionChat(session.sessionId, ()=>session.notReadCount=0)">
                          <div class="h-[100px] flex flex-row items-center border-b py-5 px-2 select-none">
                            <el-badge :value="session.notReadCount" :max="99" :show-zero="false">
                              <UserAvatar :size="60" :file-id="session.userAvatar"></UserAvatar>
                            </el-badge>
                            <div class="flex-1 ml-4 h-full">
                              <div class="flex flex-row justify-between mb-3">
                                <span>{{ session.userName }}</span>
                                <span>{{ session.messageTime }}</span>
                              </div>
                              <div>
                                {{ session.messageContent }}
                              </div>
                            </div>
                          </div>
                        </li>
                      </ul>
                      <div v-else class="text-center mt-5">
                        <el-image :src="'/svg/userCenter/empty-message.svg'" fit="cover"></el-image>
                        <p class="text-gray-300 mt-3">暂未发送或收到私信</p>
                      </div>
                    </div>
                  </div>
                  <div v-if="menuTabSelected == menuTabs.SYSTEM_NOTICE">
                    <div class="px-10 py-5 border-b">
                      <p class="font-bold text-xl">系统通知</p>
                    </div>
                    <div class="mx-10 my-8">
                      <div class="text-center mt-5">
                        <el-image :src="'/svg/userCenter/empty-notification.svg'" fit="cover"></el-image>
                        <p class="text-gray-300 mt-3">暂无系统通知</p>
                      </div>
                    </div>
                  </div>
                  <div v-if="menuTabSelected == menuTabs.PWD_UPDATE">
                    <div class="px-10 py-5 border-b">
                      <p class="font-bold text-xl">修改密码</p>
                    </div>
                    <div class="mx-10 my-8">
                      <form>
                        <div class="flex flex-row mb-8">
                          <label class="w-[120px] text-gray-500">原密码</label>
                          <div class="flex-1">
                            <el-input size="large" v-model="pwdForm.oldPwd" show-password></el-input>
                          </div>
                        </div>
                        <div class="flex flex-row mb-8">
                          <label class="w-[120px] text-gray-500">确认新密码</label>
                          <div class="flex-1">
                            <el-input size="large" v-model="pwdForm.newPwd" show-password></el-input>
                            <p class="mt-2 text-gray-500">密码长度为6～32位</p>
                          </div>
                        </div>
                        <div class="flex flex-row mb-8">
                          <label class="w-[120px] text-gray-500">确认新密码</label>
                          <div class="flex-1">
                            <el-input size="large" v-model="pwdForm.confirmNewPwd" show-password></el-input>
                          </div>
                        </div>
                        <div class="pl-[120px]">
                          <el-button type="primary" @click="submitPwdUpdate">保存设置</el-button>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SysMessageDialog v-if="showSessionChatDialog" :session-id="clickSessionId" @onClose="showSessionChatDialog = false;"></SysMessageDialog>
  </div>
</template>

<style scoped>
.menu-ul li:hover {
  background: #f8f8f8;
}

.session-item:hover {
  background: #f8f8f8;
}
</style>